用 Nest.js 開發 API 吧 (六) - TypeORM


Posted by AlanSyue on 2021-01-10

上篇分享了用 Docker 啟用 Postgresql,這次要來分享怎麼在 Nest.js 中使用 Postgresql 資料庫。

Nest.js 採用了 TypeORM,是一套用 TypeScript 編寫的 ORM 框架,支援 MySQL、Postgresql、SQLite ...等。這次會先以如何在專案上連線到上篇設定好的 Postgresql 為主:

一、安裝套件

要在 Nest.js 使用 TypeORM,要先到專案底下輸入:

yarn add @nestjs/typeorm typeorm

接著,因為這次選用 Postgresql,所以需要輸入:

yarn add pg

如果要使用 TypeORM 的 cli 指令,可以輸入:

yarn global add typeorm

二、建立 ormconfig.json

接下來要建立連線資訊,有兩個方式:

  1. 在專案根目錄下新增檔案 ormconfig.json
  2. 如果有安裝 TypeORM cli,可以輸入
typeorm init --database postgres

創建完成後,將 ormconfig.json 填寫如下設定(可參考上篇用 Nest.js 開發 API 吧 (五) - Postgresql):

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "{YOUR PASSWORD}",
  "database": "postgres",
  "synchronize": true,
  "logging": false,
  "entities": ["dist/entity/**/*.entity{.ts,.js}"],
  "migrations": ["src/migration/**/*.{.ts,.js}"],
  "subscribers": ["src/subscriber/**/*.ts"],
  "cli": {
    "entitiesDir": "src/entity",
    "migrationsDir": "src/migration",
    "subscribersDir": "src/subscriber"
  }
}

其中值得分享的是以下這段設定:

"entities": ["dist/entity/**/*.entity{.ts,.js}"]

如果是用 CLI 創建路徑會是 src/entity/**/*.ts,但實際執行會遇到無法解讀 .ts 檔案的問題,查詢了一下相關 issue 發現要去指向 build 出來的 .ts.js 檔案。所以如果要使用 migrationssubscribers,也需要將路徑做調整。

三、創建 User Entity

首先,我們先在 src 下建立 entity 的資料夾,並新增檔案 users.entity.ts,接著可以參考以下程式碼:

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity('users')
export class Users {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        type: 'varchar',
        length: 255,
    })
    email: string;

    @Column({
        type: 'varchar',
        length: 255,        
    })
    password: string;

    @Column({
        type: 'varchar',
        length: 255,
        default: null      
    })
    token: string;

    @Column({
        default: false,
    })
    is_verify: boolean;

    @Column({
        type: 'timestamp',
        default: () => 'CURRENT_TIMESTAMP(6)'
    })
    created_at: Date;

    @Column({
        type: 'timestamp',
        default: () => 'CURRENT_TIMESTAMP(6)',
        onUpdate: 'CURRENT_TIMESTAMP(6)'
    })
    updated_at: Date;
}

接著我們到 src/app.module.ts 去引入 TypeOrmModule,如下所示:

import {TypeOrmModule} from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot(),
  ],

使用 TypeOrmModule.forRoot(),他就會去 ormconfig.json 去抓取相關設定。

最後執行 yarn start:dev,並開啟 pgAdmin,就能看到 users table 被建立,只要是因為我們在 ormconfig.json 設定:

"synchronize": true,

連線時會根據 entity 的設定自動同步,如果不想自動同步可以改為 false

小結

今天分享了 Nest.js 如何利用 TypeORM 連線 Postgresql,並利用 entity 創建一張 table,下一篇預計分享關於 entity 的詳細設定,如果文章有任何錯誤或建議,歡迎告知!

NEXT:用 Nest.js 開發 API 吧 (七) - Entity


#nestjs #TypeORM #postgresql







Related Posts

LeetCode JS Easy 2704. To Be Or Not To Be

LeetCode JS Easy 2704. To Be Or Not To Be

Web Accessibility 的重要性

Web Accessibility 的重要性

找出陣列中的最大值

找出陣列中的最大值


Comments